import {
    PreviewImagesComponent,
    PHOTO_URL
} from '../../../shared/preview-image/preview-images.component';
import {
    Admin,
    Company,
    Role,
    SearchRet,
    User
} from '../../../shared/model/defination';
import { Component, OnInit, ViewChild, InjectionToken } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { AuthService } from '../../../services/auth-service';
// import { SearchRet } from '../../../services/core/base-generic-service';
import { CompanyService } from '../../../services/company-service';
import { UserService } from '../../../services/user-service';
import { Router, ActivatedRoute, Params, Route } from '@angular/router';
import { SessionService, SessionUser } from '../../../services/session-service';
import { MdlDialogService, MdlDialogReference } from '@angular-mdl/core';
import { DOMAIN, USER_ROLE } from '../../../app.config';

@Component({
    selector: 'app-index',
    templateUrl: './index.component.html',
    styleUrls: ['./index.component.scss'],
    providers: [CompanyService, UserService, MdlDialogService]
})
export class IndexComponent implements OnInit {
    public cards: any[];

    public showCards: boolean = false;

    public searchRequest: any = {};

    public domain: string = DOMAIN;

    public companies: Array<Company> = [];

    public isRoot = this._sessionService.isUserAdmin;

    public isHr = this._sessionService.isUserHr;

    public selectCompany: number;

    constructor(
        private _route: ActivatedRoute,
        private _router: Router,
        private _companyService: CompanyService,
        private _userService: UserService,
        private _dialogService: MdlDialogService,
        private _sessionService: SessionService
    ) {}

    public get BuildingId() {
        return +this._route.snapshot.params['buildingId'];
    }
    @ViewChild('confirmAlert') public confirmAlert;

    public photoPath: string;
    public count: number = 0;
    public offset: number = 0;
    public limit: number = 10;
    public deleteId: number = 0;
    public isPageLoading: boolean = false;
    public rows = [];
    public pagerMessage = {
        emptyMessage: '没有数据',
        totalMessage: '总计'
    };

    public userRole: Role;

    public search(): void {
        try {
            // this._constructQuery();
            this.page(0, 10);
        } catch (e) {
            console.error(e);
        } finally {
        }
    }
    public showDialog(photoPath: string) {
        let pDialog = this._dialogService.showCustomDialog({
            component: PreviewImagesComponent,
            providers: [
                { provide: PHOTO_URL, useValue: DOMAIN + '/' + photoPath }
            ],
            isModal: true,
            styles: { width: '350px' },
            clickOutsideToClose: true,
            enterTransitionDuration: 400,
            leaveTransitionDuration: 400
        });
        pDialog.subscribe((dialogReference: MdlDialogReference) => {
            console.log('dialog visible', dialogReference);
        });
    }
    async ngOnInit() {
        let session: Admin = await this._sessionService.getCurrentUser();
        this.userRole = session.roles[0];
        const criteria: any = { pageSize: 100 };
        if (!this._sessionService.isUserHr) {
            criteria.projectId = this._sessionService.Managable.id;
            let action$ = this._companyService.getCompanyAll(
                criteria.projectId
            );
            let searchRet: SearchRet<Company> = await action$.toPromise();
            this.companies = searchRet.items;
        }
        this.page(this.offset, this.limit);
    }
    private _getControledRoles() {
        let indexOrder = USER_ROLE.indexOf(
            this.userRole.roleName.toLowerCase()
        );
        return USER_ROLE.filter(r => USER_ROLE.indexOf(r) > indexOrder);
    }
    _constructQuery() {
        let criteria: any = {};
        if (this.searchRequest.userName) {
            criteria.userName = this.searchRequest.userName;
        }
        if (this.searchRequest.telephone) {
            criteria.mobile = this.searchRequest.telephone;
        }
        if (this._sessionService.isUserProperty) {
            criteria.projectId = this._sessionService.Managable.id;
        }
        if (this._sessionService.isUserHr) {
            criteria.companyId = this._sessionService.Managable.id;
        }
        if (typeof this.selectCompany !== 'undefined') {
            criteria.companyId = this.selectCompany;
        }
        return criteria;
    }
    async page(offset, limit) {
        try {
            this.isPageLoading = true;
            let criteria = this._constructQuery();
            criteria.pageNumber = offset + 1;
            criteria.pageSize = this.limit;
            let action$ = <Observable<
                SearchRet<Admin>
            >>this._userService.Search(criteria);
            let searchRet: any = await action$.toPromise();
            searchRet.items.map(item => {
                item.photos = item.identy_photos;
                return item;
            });
            this.cards = searchRet.items;
            this.count = searchRet.totalPageRecords;
            const start = offset * limit;
            const end = start + limit;
            const rows = [...this.rows];
            console.log(this.rows);
            for (let i = start; i < end; i++) {
                rows[i] = searchRet.items[i - start];
            }

            // this.rows = rows;
            this.rows = searchRet.items;
            this.isPageLoading = false;
            console.log('Page Results', start, end, rows);
        } catch (e) {
            console.info(e);
            if (e.errCode === 401) {
                this._router.navigate(['/login']);
            }
        } finally {
        }
    }

    async delete(id) {
        try {
            await this._dialogService
                .confirm('确定删除此人员？', '取消', '确认')
                .toPromise();
            await this._userService.Delete(+id).toPromise();
            await this.ngOnInit();
        } catch (e) {
            console.log(e);
        } finally {
        }
    }

    previewPhoto(facePath: string) {
        this.photoPath = facePath;
        // this._dialogService.alert()
    }

    onPage(event) {
        console.log('Page Event', event);
        this.page(event.offset, event.limit);
    }
}
